

package com.hikvision.cms.mq;



import com.google.protobuf.ByteString;
import com.hikvision.cms.api.eps.beds.EventDis;
import com.hikvision.cms.common.util.MessageUtil;
import com.hikvision.cms.domain.Plate;
import com.hikvision.park.proto.PassVehicleMsg;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jms.*;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.text.MessageFormat;

public class ActiveMQConnect
{

	private static final Logger log = LoggerFactory.getLogger(ActiveMQConnect.class);
	private static ActiveMQConnect activeMQConnect = new ActiveMQConnect();
	private static Connection connection = null;




	private ActiveMQConnect()
	{
	}

	public static ActiveMQConnect getInstance()
	{
		return activeMQConnect;
	}

	public void receiveMessage()
	{

		String url = "tcp://60.190.232.83:61616";
		String topicName = "passvehicle.nbgxq";
		String clientID = "client2018070718";
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER,
				ActiveMQConnectionFactory.DEFAULT_PASSWORD,url);
		try
		{

			connection = connectionFactory.createConnection();
			connection.setClientID(clientID);
			connection.start();
			Session session = connection.createSession(Boolean.FALSE.booleanValue(), 1);
			Topic topic = session.createTopic(topicName);
			MessageConsumer consumer = session.createDurableSubscriber(topic, clientID);
			MessageUtil.writeReceiveMsg("mq开始启动!");
			do
			{
				BytesMessage bytesMessage = (BytesMessage)consumer.receive(0x5f5e100L);

				if (null != bytesMessage)
				{

					long length = bytesMessage.getBodyLength();
					byte[] bt = new byte[(int)length];
					// 将BytesMessage转换为byte类型
					bytesMessage.readBytes(bt);
					// 壳文件字段，EventDis类为event_dis.proto文件解析而来，CommEventLog类为事件壳文件类
					EventDis.CommEventLog parseFrom = EventDis.CommEventLog.parseFrom(bt);
					// 输出壳文件字段
					 log.info("输出壳文件字段"+parseFrom.toString());
					// 扩展字段，此字段为设备上报事件内容，部分事件需要使用pb文件再次解析
					ByteString extInfo = parseFrom.getExtInfo();
					// 输出扩展字段
					log.info("输出扩展字段"+extInfo.toStringUtf8());
				}
			} while (true);
		}
		catch (Exception e)
		{
			log.error("error", e);
			MessageUtil.writeReceiveMsg("mq启动失败");
		}
	}

	public void stop()
	{
		try
		{
			if (null != connection)
				connection.close();
			MessageUtil.writeReceiveMsg("mq启动停止");
		}
		catch (Throwable throwable) { }
	}

}
